package com.hefan.schedule.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 定时任务切面
 *
 * @version 1.0.0
 */
public class ScheduleAspect {

  public void before(JoinPoint joinPoint) {
    // 目标类
    Object target = joinPoint.getTarget();
    // 目标类Class字节码
    Class<?> targetClass = target.getClass();
    // 目标方法的签名
    Signature signature = joinPoint.getSignature();
    // 目标方法名
    String methodName = signature.getName();
    // 目标方法的参数类型数组
    Class<?>[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();

    try {
      Scheduled schedule = null;
      Method method = targetClass.getMethod(methodName, parameterTypes);
      if (method != null && method.isAnnotationPresent(Scheduled.class)) {
        // 获取方法上的设置
        schedule = method.getAnnotation(Scheduled.class);
      }

      if (schedule != null) {

      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 完成事务操作后，清除数据源设置
   *
   * @param joinPoint
   */
  public void after(JoinPoint joinPoint) {
    // 目标类
    Object target = joinPoint.getTarget();
    // 目标类Class字节码
    Class<?> targetClass = target.getClass();
    // 目标方法的签名
    Signature signature = joinPoint.getSignature();
    // 目标方法名
    String methodName = signature.getName();
    // 目标方法的参数类型数组
    Class<?>[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();
    try {
      Scheduled schedule = null;
      Method method = targetClass.getMethod(methodName, parameterTypes);
      if (method != null && method.isAnnotationPresent(Scheduled.class)) // 获取方法上的数据源设置
        schedule = method.getAnnotation(Scheduled.class);
      else if (targetClass.isAnnotationPresent(Scheduled.class)) // 获取类上的数据源设置
        schedule = targetClass.getAnnotation(Scheduled.class);

      if (schedule != null) {

      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
